package dao.impl;

import dao.UserDao;
import dao.domain.Assistant;
import dao.domain.Client;
import dao.domain.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;

/**
 * @author huangzhiyang
 * @Date 2023/11/7
 * @Description
 */
public class UserDaoImpl extends BaseDaoImpl implements UserDao {

    /**
     * 登录
     *
     * @param user:数据库表的名称，一般要使用的类类名一致
     * @param account:账号
     * @param password:密码
     * @return UserDao
     */
    @Override
    public User login(String user, String account, String password) throws SQLException {
        String sql = "select * from " + user + " where account=? and password=?";
        Connection conn = super.getConnection();
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, account);
        pstmt.setString(2, password);
        ResultSet res = pstmt.executeQuery();
        return getSelectedUserDao(conn, pstmt, user, res);
    }

    /**
     * 只通过账号找数据
     *
     * @param user:表类型
     * @param account：账号
     */
    @Override
    public User selectByAccount(String user, String account) throws SQLException {
        String sql = "select * from " + user + " where account=?";
        Connection conn = super.getConnection();
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, account);
        ResultSet res = pstmt.executeQuery();
        return getSelectedUserDao(conn, pstmt, user, res);
    }

    private User getSelectedUserDao(Connection conn, PreparedStatement pstmt,
                                    String user, ResultSet res) throws SQLException {
        User userDao = null;
        String userType1 = "client";
        String userType2 = "assistant";
        if (res != null && res.next()) {
            if (Objects.equals(user, userType1)) {
                userDao = new Client(
                        res.getString("account"),
                        res.getString("name"),
                        res.getString("password"),
                        res.getDate("registrationTime"),
                        res.getInt("amount"),
                        res.getInt("consumption"));
            } else if (Objects.equals(user, userType2)) {
                userDao = new Assistant(
                        res.getString("account"),
                        res.getString("password")
                );
            }
        } else {
            System.out.println("fall");
        }
        super.closeAll(conn, pstmt, res);
        return userDao;
    }
}
